package com.example.tomatotodo;

import android.app.AlertDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.tomatotodo.adapter.TodoAdapter;
import com.example.tomatotodo.model.TodoConstants;
import com.example.tomatotodo.model.TodoItem;
import com.example.tomatotodo.model.TodoSettingDTO;
import com.example.tomatotodo.ui.AddTodoDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class TodoFragment extends Fragment {
    private static final String TAG = "TodoFragment";

    private RecyclerView recyclerView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private TodoAdapter adapter;
    private List<TodoItem> todoList;
    private SharedPreferences sharedPreferences;
    private Gson gson;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_todo, container, false);

        recyclerView = view.findViewById(R.id.todo_recycler);
        swipeRefreshLayout = view.findViewById(R.id.swipe_refresh);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        sharedPreferences = getActivity().getSharedPreferences("todo_data", Context.MODE_PRIVATE);
        gson = new Gson();
        loadTodoList();

        adapter = new TodoAdapter(todoList);
        recyclerView.setAdapter(adapter);

        // 设置下拉刷新监听器
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshTodoList();
            }
        });

        // 设置长按删除监听器
        adapter.setOnItemLongClickListener(this::showDeleteConfirmationDialog);

        // 设置点击编辑监听器
        adapter.setOnItemClickListener(this::showEditTodoDialog);

        // 为加号按钮添加点击事件
        View btnAdd = view.findViewById(R.id.btn_add);
        btnAdd.setOnClickListener(v -> showAddTodoDialog());

        return view;
    }

    private void loadTodoList() {
        String todoListJson = sharedPreferences.getString("todo_list", null);
        if (todoListJson != null) {
            Type type = new TypeToken<List<TodoItem>>() {
            }.getType();
            todoList = gson.fromJson(todoListJson, type);
        } else {
            // 如果没有保存的数据，则使用默认数据
            todoList = new ArrayList<>();
            TodoSettingDTO example1 = new TodoSettingDTO(
                    "点击右上角“➕”添加待办", TodoConstants.TYPE_POMODORO, TodoConstants.TIMER_MODE_NO_TIMER, 25,
                    null, null, null, null, null);
            TodoSettingDTO example2 = new TodoSettingDTO(
                    "点击可修改待办", TodoConstants.TYPE_POMODORO, TodoConstants.TIMER_MODE_NO_TIMER, 25,
                    null, null, null, null, 2);
            TodoSettingDTO example3 = new TodoSettingDTO(
                    "长按可删除待办", TodoConstants.TYPE_GOAL, TodoConstants.TIMER_MODE_NO_TIMER, null,
                    "2025-09-01", TodoConstants.GOAL_TARGET_TYPE_TIMES, 7, null, null);
            todoList.add(new TodoItem(example1));
            todoList.add(new TodoItem(example2));
            todoList.add(new TodoItem(example3));
            saveTodoList(); // 保存默认数据
        }
    }

    private void saveTodoList() {
        String todoListJson = gson.toJson(todoList);
        Log.d(TAG, "saveTodoList: todoListJson =\n" + todoListJson);
        sharedPreferences.edit().putString("todo_list", todoListJson).apply();
    }

    /**
     * 刷新待办列表
     */
    private void refreshTodoList() {
        // 重新加载数据
        loadTodoList();
        adapter.notifyDataSetChanged();

        // 停止刷新动画
        swipeRefreshLayout.setRefreshing(false);

        // 显示刷新完成提示
        if (getContext() != null) {
            Toast.makeText(getContext(), "刷新完成", Toast.LENGTH_SHORT).show();
        }
    }

    private void showAddTodoDialog() {
        AddTodoDialog dialog = new AddTodoDialog(getContext(), newItem -> {
            todoList.add(newItem);
            adapter.notifyItemInserted(todoList.size() - 1);
            saveTodoList();
        });
        dialog.show();
    }

    // 添加编辑Todo对话框方法
    private void showEditTodoDialog(int position) {
        if (position < 0 || position >= todoList.size()) {
            Log.w(TAG, "无效的位置索引: " + position + ", 列表大小: " + todoList.size());
            return;
        }

        TodoItem itemToEdit = todoList.get(position);
        AddTodoDialog dialog = new AddTodoDialog(getContext(), newItem -> {
            // 更新列表中的项目
            todoList.set(position, newItem);
            adapter.notifyItemChanged(position);
            saveTodoList();
        }, itemToEdit); // 使用新的构造函数传递要编辑的项目
        dialog.show();
    }

    private void showDeleteConfirmationDialog(int position) {
        // 检查位置是否有效
        if (position < 0 || position >= todoList.size()) {
            Log.w(TAG, "无效的位置索引: " + position + ", 列表大小: " + todoList.size());
            return;
        }

        new AlertDialog.Builder(getContext())
                .setTitle("确认删除")
                .setMessage("确定要删除这个待办事项吗？")
                .setPositiveButton("确定", (dialog, which) -> {
                    deleteTodoItem(position);
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void deleteTodoItem(int position) {
        Log.d(TAG, "开始删除待办事项，位置: " + position + ", 列表大小: " + todoList.size());

        // 检查位置是否有效
        if (position < 0 || position >= todoList.size()) {
            Log.w(TAG, "删除操作中发现无效的位置索引: " + position + ", 列表大小: " + todoList.size());
            return;
        }

        // 获取要删除的项目信息用于日志记录
        TodoItem itemToDelete = todoList.get(position);
        Log.d(TAG, "删除项目信息 - 名称: " + itemToDelete.getName() + ", 类型: " + itemToDelete.getType());

        // 从数据列表中移除
        todoList.remove(position);
        Log.d(TAG, "从数据列表中移除项目，位置: " + position + ", 移除后列表大小: " + todoList.size());

        // 通知adapter项目已移除
        adapter.notifyItemRemoved(position);
        // 保存更新后的列表
        saveTodoList();
        Log.i(TAG, "删除操作完成，已保存更新后的列表");
    }
}